package com.taotao.web.service;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.taotao.common.service.HttpClientService;
import com.taotao.common.service.RedisService;
import com.taotao.web.pojo.ItemVO;

@Service
public class ItemService {

	@Autowired
	private HttpClientService httpClientService;
	
	@Autowired
	private RedisService redisService;
	
	@Value("${TATAO_MANAGE_ITEM}")
	private String TATAO_MANAGE_ITEM;
	
	@Value("${TAOTAO_WEB_ITEM_CACHE_PREFIX}")
	private String TAOTAO_WEB_ITEM_CACHE_PREFIX;
	
	@Value("${TAOTAO_WEB_ITEM_CACHE_TIMEOUT}")
	private Long TAOTAO_WEB_ITEM_CACHE_TIMEOUT;

	/**
	 * 根据id查询商品详情
	 * 
	 * @param itemId
	 * @return
	 */
	public ItemVO queryItemById(Long itemId) {
		
		// 查询缓存
		try {
			ItemVO itemVO = this.redisService.get(TAOTAO_WEB_ITEM_CACHE_PREFIX + itemId, new TypeReference<ItemVO>() {
			});
			if(itemVO != null){
				return itemVO;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		// 调用后台接口获取数据
		ItemVO itemVO = this.httpClientService.doGet(TATAO_MANAGE_ITEM + itemId,
				new TypeReference<ItemVO>() {
				});
		
		// 添加缓存
		try {
			this.redisService.set(TAOTAO_WEB_ITEM_CACHE_PREFIX + itemId, itemVO, TAOTAO_WEB_ITEM_CACHE_TIMEOUT);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
		return itemVO;
	}

}
